package com.oocl.servlet.action;

import static com.oocl.util.IPPropertiesUtil.getProperty;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.pojo.Constants;
import com.oocl.pojo.Dish;
import com.oocl.pojo.JSONResponse;
import com.oocl.pojo.Merchant;
import com.oocl.pojo.Protocol;
import com.oocl.service.DishManager;
import com.oocl.service.DishTypeManager;
import com.oocl.service.MerchantManager;
import com.oocl.service.factory.DishManagerFactory;
import com.oocl.service.factory.DishTypeManagerFactory;
import com.oocl.service.factory.MerchantManagerFactory;
import com.oocl.util.DESUtil;
import com.oocl.util.HTTPConnUtil;
import com.oocl.util.ValidateUtil;

/**
 * Servlet implementation class SearchDishServlet
 */
@WebServlet("/sec/dishes/search.action")
public class SearchDishesActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MerchantManager merchantManager = MerchantManagerFactory.getInstance();
	private DishManager dishManager = DishManagerFactory.getInstance();
	ObjectMapper mapper = new ObjectMapper();
	String jsonStr;
	private final String GET_MERCHANTS_URL = String.format("http://%s:%s/O2OAdministrator/getMerchant", getProperty("admin.ipaddr"), getProperty("admin.port"));
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("UTF-8");                      //解决中文乱码
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("content-type","text/html;charset=UTF-8");//解决中文乱码
		Integer code = 1;
		
		String mid = request.getParameter("mid");
		String _dType = request.getParameter("dtype");
		String _keyword = request.getParameter("keyword");
		Integer dType = 0;
		String keyword = null;
		if (!ValidateUtil.isNullOrEmpty(_dType)) {
			dType = Integer.parseInt(_dType);
		}
		if (!ValidateUtil.isNullOrEmpty(_keyword)) {
			keyword = _keyword;
		}
		Merchant merchant = merchantManager.findOneMerchantById(mid);
		
		// get allowed mid list
		String merchantsJson = HTTPConnUtil.sendGet(GET_MERCHANTS_URL);
		System.out.println(merchantsJson);
		if (ValidateUtil.isNullOrEmpty(merchantsJson)) {
//		if (false) {
			code=-1;
			JSONResponse<Dish> jsonResponse = new JSONResponse<Dish>();
			jsonResponse.setCode(code);
			jsonResponse.setMsg("平台端异常!");
			jsonStr = mapper.writeValueAsString(jsonResponse);
			PrintWriter out = response.getWriter();
			out.println(jsonStr);
			return;
		}

		merchantsJson = merchantsJson.replaceAll(" ", "+");
		merchantsJson = new DESUtil().decrypt(merchantsJson,"UTF-8");
		System.out.println(merchantsJson);
		Protocol p = new ObjectMapper().readValue(merchantsJson, Protocol.class);	
		@SuppressWarnings("unchecked")
		List<String> listObj = (List<String>) p.getMsgObj();
		List<String> allAllowedMid = merchantManager.MerchantsIdFilterByStatus(listObj);
		
		//79fb5a6c-a7b4-4daa-9c12-a5408bcf1765
//		List<String> allAllowedMid = new ArrayList<String>();//test
//		allAllowedMid.add("61e31569-e8c1-4fbe-a737-7e499ade1c94");//test
//		allAllowedMid.add("79fb5a6c-a7b4-4daa-9c12-a5408bcf1765");//test
		if (merchant == null || !merchant.getmStatus().equals(Constants.APPLY_PASSED) || !allAllowedMid.contains(merchant.getmId())) {
			code=0;
			JSONResponse<Dish> jsonResponse = new JSONResponse<Dish>();
			jsonResponse.setCode(code);
			jsonResponse.setMsg("你所请求的商家不存在/未过审/或已被拉黑!");
			jsonStr = mapper.writeValueAsString(jsonResponse);
			PrintWriter out = response.getWriter();
			out.println(jsonStr);
			return;
		}
		
		List<Dish> dishList = dishManager.findDishes(dType, keyword, mid);
		JSONResponse<Dish> jsonResponse = new JSONResponse<Dish>();
		jsonResponse.setCode(code);
		jsonResponse.setMsg("搜索成功");
		jsonResponse.setResultList(dishList);
		jsonStr = mapper.writeValueAsString(jsonResponse);
		PrintWriter out = response.getWriter();
		out.println(jsonStr);
		
//		response.sendRedirect("../dishes?mid=" + mid + "&dtype=" + dType + "&keyword=" + keyword);
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doPost(request, response);
	}

}
